<template>
    <div class="effects-panel" :style="panelStyle" @mousedown="handleMouseDown" @mousemove="handleMouseMove"
        @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
        <div v-for="toggle in toggleSwitches" :key="toggle.name" class="toggle"
            :style="{ left: toggle.left, top: toggle.top }">
            <toggle-switch @switchToggle="handleSwitchToggle(toggle.name, $event)"></toggle-switch>
        </div>
        <div v-for="knob in knobs" :key="knob.label" class="knob-container" :style="{ left: knob.left, top: knob.top }">
            <level-indicator v-if="knob.label === 'INPUT' || knob.label === 'OUTPUT'" :label="knob.label"
                :style="getLevelIndicatorStyle(knob.label)"></level-indicator>
            <knob :label="knob.label" @knob-change="handleKnobChange" @valueChange="handleValueChange"></knob>
        </div>
    </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import Knob from './BottomKnob.vue';
import ToggleSwitch from './BottomSwitch.vue';
import LevelIndicator from './LevelIndicator.vue';
import { getAssetPath } from '../utils/assetPath';

export default {
    name: 'EffectsPanel',
    components: { Knob, ToggleSwitch, LevelIndicator },
    setup() {
        const toggleSwitches = ref([
            { name: 'NOISE GATE', left: '19.6%', top: '40%', processorId: 1 },
            { name: 'DELAY', left: '35.2%', top: '40%', processorId: 6 },
            { name: 'REVERB', left: '65.7%', top: '40%', processorId: 7 },
        ]);

        const knobs = ref([
            { label: 'INPUT', left: '8.1%', top: '54%', value: 0 },
            { label: 'THRESHOLD', left: '25.6%', top: '54%', value: 0 },
            { label: 'TIME', left: '40.1%', top: '54%', value: 0 },
            { label: 'FEEDBACK', left: '48.9%', top: '54%', value: 0 },
            { label: 'MIX', left: '57.7%', top: '54%', value: 0 },
            { label: 'REVERB MIX', left: '71.9%', top: '54%', value: 0 },
            { label: 'OUTPUT', left: '85.5%', top: '54%', value: 0 }
        ]);

        const isDragging = ref(false);
        const dragStartX = ref(0);
        const dragStartY = ref(0);
        const currentKnob = ref(null);
        const leftShift = ref('0px');

        const backgroundImageUrl = computed(() => {
            // const publicPath = __webpack_public_path__ || '@/';
            // return `${publicPath}assets/bottom.png`;
            return getAssetPath('bottom.png');
        });

        const panelStyle = computed(() => ({
            left: leftShift.value,
            // backgroundImage: `url(${backgroundImageUrl.value})`,
        }));

        const handleMouseDown = (event) => {
            if (event.target.closest('.level-indicator')) {
                event.preventDefault();
                return;
            }
            isDragging.value = true;
            dragStartX.value = event.clientX;
            dragStartY.value = event.clientY;
            currentKnob.value = event.target.closest('.knob-container');
        };

        const handleMouseMove = (event) => {
            if (!isDragging.value || !currentKnob.value) return;
            const deltaY = dragStartY.value - event.clientY;
            const knobLabel = currentKnob.value.querySelector('.knob').getAttribute('label');
            const knob = knobs.value.find(k => k.label === knobLabel);
            if (knob) {
                knob.value = Math.min(100, Math.max(0, knob.value + deltaY / 2));
                emit('knob-change', { label: knob.label, value: knob.value });
            }
            dragStartY.value = event.clientY;
        };

        const handleMouseUp = () => {
            isDragging.value = false;
            currentKnob.value = null;
        };

        const getLevelIndicatorStyle = (label) => ({
            pointerEvents: 'none'
        });

        const handleKnobChange = (data) => {
            const knob = knobs.value.find(k => k.label === data.label);
            if (knob) {
                knob.value = data.value;
            }
            emit('effect-change', data);
        };

        const handleValueChange = ({ label, value }) => {
            // console.log(`Knob ${label} changed to ${value}`);
            window.electronAPI.sendKnobValue(label, value);
        };

        const handleSwitchToggle = (switchName, isOn) => {
            console.log(`Switch ${switchName} is now ${isOn ? 'ON' : 'OFF'}`);
            const toggle = toggleSwitches.value.find(t => t.name === switchName);
            if (toggle) {
                console.log(`Sending bypass state for processor ${toggle.processorId}: ${!isOn}`);
                window.electronAPI.setProcessorBypass(toggle.processorId, !isOn);
            } else {
                console.error(`Toggle switch not found for ${switchName}`);
            }
        };

        return {
            toggleSwitches,
            knobs,
            handleMouseDown,
            handleMouseMove,
            handleMouseUp,
            getLevelIndicatorStyle,
            handleKnobChange,
            panelStyle,
            handleValueChange,
            handleSwitchToggle
        };
    }
};
</script>

<style scoped>
.effects-panel {
    background-image: url('../assets/bottom.png');
    background-size: 100%;
    background-position: bottom;
    background-repeat: no-repeat;
    height: 300px;
    size: 80%;
    display: flex;
    padding: 20px;
    border-radius: 10px;
    position: relative;
    user-select: none;
}

.toggle,
.knob-container {
    position: absolute;
}

.level-indicator {
    pointer-events: none;
}
</style>